package net.wanho.controller;

import com.aliyun.oss.OSSClient;
import lombok.SneakyThrows;
import net.wanho.vo.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * Author：汤小洋
 * Date：2024-01-12 14:27
 * Description：<描述>
 */
@RestController
public class FileController {

    @Resource
    private OSSClient ossClient;

    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;

    @SneakyThrows
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam MultipartFile file){
        String dir = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDateTime.now());
        String filename = file.getOriginalFilename();
        String objectName = dir + "/" + UUID.randomUUID() + filename.substring(filename.lastIndexOf("."));

        ossClient.putObject(bucket, objectName, file.getInputStream());

        // 生成文件访问路径
        String  url = "https://" + bucket + "." + endpoint + "/" + objectName;

        return AjaxResult.success(url);

    }

}
